package com.zdya.combatdocuments.exception;

import com.zdya.combatdocuments.entity.vo.ResultVo;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * * @author: bj
 * * @date: 2023/6/2
 * * @desc: 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionAop {

    /**
     * 处理服务异常
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ResultVo> errorHandler(BusinessException e) {
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(e.getCode());
        resultVo.setMsg(e.getMessage());
        e.printStackTrace();
        return ResponseEntity.status(200).body(resultVo);
    }

    /**
     * 处理参数校验异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<ResultVo> errorHandler(MethodArgumentNotValidException e) {
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(500);
        resultVo.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        e.printStackTrace();
        return ResponseEntity.status(200).body(resultVo);
    }

    /**
     * 处理系统异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ResultVo> errorHandler(Exception e) {
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(500);
        resultVo.setMsg(e.getMessage());
        e.printStackTrace();
        return ResponseEntity.status(200).body(new ResultVo(500, e.getMessage()));
    }

}
